package com.blog.controller.admin;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.blog.entity.User;
import com.blog.service.UploadService;

@Controller
public class Upload {
	//注入uploadService
	@Autowired
	private UploadService uploadService;
	/**
	 * 跳转到上传界面
	 */
	@RequestMapping(value="/uploadPage.do",method=RequestMethod.GET)
	public String uploadPage(){
		
		return "uploadPage";
	}
	/**
	 * 上传头像图片
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value="/upload.do",method=RequestMethod.POST)
	public String addUserInfo(MultipartFile file,Model model,User user) throws Exception{
		/**
         * 上传图片
         */
    	//图片上传成功后，将图片的地址写到数据库
    	String filePath = "E:\\upload";//保存图片的路径
    	//获取原始图片的拓展名
    	String originalFilename = file.getOriginalFilename();
    	//新的文件名字
    	String newFileName = UUID.randomUUID()+originalFilename;
    	System.out.println(newFileName);
    	File targetFile = new File(filePath,newFileName);
    
    	file.transferTo(targetFile);
        user.setPhoto(newFileName);
        
        uploadService.upload(user);
		return "success";
	}
}
